package pers.smalltown.ourspace.record;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RecordDeal {
	@Autowired
	private OurRecordDao ourRecordDao;
	
	public List<Record> deal(String platform) throws Exception {
		
		System.out.println("RecordDeal Begin...");
		String filePath;
		String errorPath;
		if (platform.equals("QQ")) {
			filePath = "C:/Users/luhha/Desktop/maybelast/qq.html";
			errorPath = "C:/Users/luhha/Desktop/maybelast/errorQQ.log";
		} else if (platform.equals("WX")) {
			filePath = "C:/Users/luhha/Desktop/maybelast/wechat.html";
			errorPath = "C:/Users/luhha/Desktop/maybelast/errorWX.log";
		} else {
			throw new Exception("Platfrom " + platform + " not support");
		}
		BufferedReader in = new BufferedReader(new FileReader(filePath));
		BufferedWriter writer = new BufferedWriter(new FileWriter(errorPath));
		int batchSize = 300;
		String str ;
		Pattern recordPattern = Pattern.compile("(.*?)\\+{4}([\\s\\S]*?)\\+{4}(.*)");
		
		List<Record> dealList = new ArrayList<>();
		for (int i = 0, num = 0; (str = in.readLine()) != null; i++, num++) {
			Matcher matcher = recordPattern.matcher(str);
			if (matcher.find()) {
				int groupNum = matcher.groupCount();
				if (groupNum != 3) {
					writer.append("数据行处理错误，修正处理：增加到上一条内容中, " + num  + "\n");
					Record lastData = dealList.get(dealList.size()-1);
					lastData.setContent(lastData.getContent() + str);
				} else {
					dealList.add(new Record(matcher.group(1), matcher.group(3), matcher.group(2), platform));
				}
			} else {
				writer.append("数据行处理错误，修正处理：增加到上一条内容中, " + num + "\n");
				Record lastData = dealList.get(dealList.size()-1);
				lastData.setContent(lastData.getContent() + str);
			}
			
			if (i % batchSize == 0) {
				ourRecordDao.insertBatch(dealList);
				dealList.clear();
			}
		}
		if (dealList.size() > 0) {
			ourRecordDao.insertBatch(dealList);
		}
		
		in.close();
		writer.close();
		return dealList;
	}
}
